/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.gxarea.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.gxarea.entity.Community;
import com.jeeplus.modules.gxarea.service.CommunityService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;

/**
 * 点位Controller
 * @author azj
 * @version 2024-09-04
 */
@RestController
@RequestMapping(value = "/gxarea/community")
public class CommunityController extends BaseController {

	@Autowired
	private CommunityService communityService;

	@ModelAttribute
	public Community get(@RequestParam(required=false) String id) {
		Community entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = communityService.get(id);
		}
		if (entity == null){
			entity = new Community();
		}
		return entity;
	}

	/**
	 * 点位列表数据
	 */
	@RequiresPermissions("gxarea:community:list")
	@GetMapping("list")
	public AjaxJson list(Community community, HttpServletRequest request, HttpServletResponse response) {
		return AjaxJson.success().put("page",communityService.findPageList(new Page<Community>(request, response), community));
	}

	/**
	 * 根据Id获取点位数据
	 */
	@RequiresPermissions(value={"gxarea:community:view","gxarea:community:add","gxarea:community:edit"},logical=Logical.OR)
	@GetMapping("queryById")
	public AjaxJson queryById(Community community) {
		return AjaxJson.success().put("community", community);
	}

	/**
	 * 保存点位
	 */
	@RequiresPermissions(value={"gxarea:community:add","gxarea:community:edit"},logical=Logical.OR)
	@PostMapping("save")
	public AjaxJson save(Community community, Model model) throws Exception{
		/**
		 * 后台hibernate-validation插件校验
		 */
		String errMsg = beanValidator(community);
		if (StringUtils.isNotBlank(errMsg)){
			return AjaxJson.error(errMsg);
		}
		//新增或编辑表单保存
		communityService.save(community);//保存
		return AjaxJson.success("保存点位成功");
	}


	/**
	 * 批量删除点位
	 */
	@RequiresPermissions("gxarea:community:del")
	@DeleteMapping("delete")
	public AjaxJson delete(String ids) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			communityService.delete(communityService.get(id));
		}
		return AjaxJson.success("删除点位成功");
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("gxarea:community:export")
    @GetMapping("export")
    public AjaxJson exportFile(Community community, HttpServletRequest request, HttpServletResponse response) {
		try {
            String fileName = "点位"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Community> page = communityService.findPage(new Page<Community>(request, response, -1), community);
    		new ExportExcel("点位", Community.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error("导出点位记录失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("gxarea:community:import")
    @PostMapping("import")
   	public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Community> list = ei.getDataList(Community.class);
			for (Community community : list){
				try{
					communityService.save(community);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条点位记录。");
			}
			return AjaxJson.success( "已成功导入 "+successNum+" 条点位记录"+failureMsg);
		} catch (Exception e) {
			return AjaxJson.error("导入点位失败！失败信息："+e.getMessage());
		}
    }

	/**
	 * 下载导入点位数据模板
	 */
	@RequiresPermissions("gxarea:community:import")
    @GetMapping("import/template")
     public AjaxJson importFileTemplate(HttpServletResponse response) {
		try {
            String fileName = "点位数据导入模板.xlsx";
    		List<Community> list = Lists.newArrayList();
    		new ExportExcel("点位数据", Community.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			return AjaxJson.error( "导入模板下载失败！失败信息："+e.getMessage());
		}
    }
	/**
	 * 获取上级点位列表
	 */
	@GetMapping("getAreaByType")
	public AjaxJson getAreaByType() {
		return AjaxJson.success().put("data", communityService.getAreaByType());
	}

	/**
	 * 获取业务前缀字典
	 */
	@GetMapping("getDictTypeChar")
	public AjaxJson getDictTypeChar() {
		return AjaxJson.success().put("data", communityService.getDictTypeChar());
	}

	/**
	 * 获取点位用户列表
	 */
	@GetMapping("userListByCode")
	public AjaxJson userListByCode(String areacode) {
		return AjaxJson.success().put("data", communityService.userListByCode(areacode));
	}
	/**
	 * 获取所有用户信息
	 */
	@GetMapping("userList")
	public AjaxJson userList() {
		return AjaxJson.success().put("data", communityService.userList());
	}
	/**
	 * 设备max绑定检查
	 */
	@GetMapping("maxCheck")
	public AjaxJson maxCheck(String max) {
		return AjaxJson.success().put("data", communityService.maxCheck(max));
	}


	/**
	 * getWinByIdList
	 *获取该区域窗口信息 获取该区域业务信息
	 * @author azj
	 * @date 2020-05-18/下午1:43:15
	 */
	@GetMapping("getWinByIdList")
	public AjaxJson getWinByIdList(String id){
		return AjaxJson.success().put("windata", communityService.getWinByIdList(id)).put("typedata", communityService.getTypeByIdList(id));
	}
}